package com.zhongc.advance.web.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;


/**
 * 
 * 
 *                       
 * @Filename AccessFilter.java
 *
 * @Description 
 *
 * @Version 1.0
 *
 * @Author zhongc
 *
 * @Email zhong_ch@foxmail.com
 *       
 * @History 
 *<li>Author: zhongc</li>
 *<li>Date: 2015年7月13日</li>
 *<li>Version: 1.0</li>
 *<li>Content: create</li>
 *
 */
public class AccessFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		chain.doFilter(new AccessHttpServletRequestWrapper((HttpServletRequest)request), response);
	}

	@Override
	public void destroy() {

	}
	
	private class AccessHttpServletRequestWrapper extends HttpServletRequestWrapper{

		private AccessHttpServletRequestWrapper(HttpServletRequest request) {
			super(request);
		}

		@Override
		public String getParameter(String name) {
			return process(name, super.getParameter(name));
		}

		@Override
		public Map<String, String[]> getParameterMap() {
			Map<String, String[]> map = new HashMap<String, String[]>(super.getParameterMap());
			Iterator<Map.Entry<String, String[]>> entries = map.entrySet().iterator();
			while(entries.hasNext()){
				Map.Entry<String, String[]> entry = entries.next();
				entry.setValue(process(entry.getKey(), entry.getValue()));
			}
			return map;
		}

		@Override
		public String[] getParameterValues(String name) {
			return process(name, super.getParameterValues(name));
		}
		
	}
	
	private String[] process(String key, String[] values){
		if(values == null || values.length < 1){
			return values;
		}
		for (int i = 0; i < values.length; i++) {
			values[i] = process(key, values[i]);
		}
		return values;
	}
	
	private String process(String key, String value) {
		return (value == null || value.trim().length() < 1) ? null : value;
	}
}
